// 商品数据
const products = [
    {
        id: 1,
        name: "智能手机 X1",
        price: 2999,
        originalPrice: 3499,
        image: "./image/智能手机.jpeg",
        description: "高性能智能手机，6.5英寸全面屏，128GB存储，4800万像素摄像头",
        category: "电子产品",
        sales: 1250,
        stock: 50
    },
    {
        id: 2,
        name: "无线蓝牙耳机",
        price: 199,
        originalPrice: 299,
        image: "./image/无线蓝牙耳机.jpeg",
        description: "真无线蓝牙耳机，高音质，长续航，舒适佩戴",
        category: "电子产品",
        sales: 3200,
        stock: 120
    },
    {
        id: 3,
        name: "男士休闲T恤",
        price: 89,
        originalPrice: 129,
        image: "./image/男士休闲T恤.jpeg",
        description: "纯棉男士休闲T恤，多种颜色可选，舒适透气",
        category: "服装",
        sales: 890,
        stock: 75
    },
    {
        id: 4,
        name: "家用空气净化器",
        price: 899,
        originalPrice: 1299,
        image: "./image/空气净化器.jpg",
        description: "高效家用空气净化器，智能感应，静音设计",
        category: "家居",
        sales: 430,
        stock: 30
    },
    {
        id: 5,
        name: "有机燕麦片",
        price: 39.9,
        originalPrice: 49.9,
        image: "./image/有机燕麦片.jpg",
        description: "有机燕麦片，无添加，高纤维，健康早餐选择",
        category: "食品",
        sales: 2100,
        stock: 200
    },
    {
        id: 6,
        name: "运动跑步鞋",
        price: 259,
        originalPrice: 399,
        image: "./image/运动鞋.jpeg",
        description: "轻便运动跑步鞋，透气网面，缓震设计",
        category: "服装",
        sales: 680,
        stock: 45
    }
];

// 用户数据
let users = [
    { username: "user1", password: "123456", email: "user1@example.com" }
];

// 当前用户和购物车
let currentUser = null;
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// DOM元素
const loginPage = document.getElementById('login-page');
const registerPage = document.getElementById('register-page');
const appPage = document.getElementById('app-page');
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const showRegisterLink = document.getElementById('show-register');
const showLoginLink = document.getElementById('show-login');
const logoutBtn = document.getElementById('logout-btn');
const menuToggle = document.getElementById('menu-toggle');
const sidebar = document.getElementById('sidebar');
const sidebarUsername = document.getElementById('sidebar-username');
const cartIcon = document.getElementById('cart-icon');
const cartCount = document.getElementById('cart-count');
const contentPages = document.querySelectorAll('.content-page');
const menuItems = document.querySelectorAll('.menu-item');
const footerItems = document.querySelectorAll('.footer-item');
const featuredProductsGrid = document.getElementById('featured-products');
const allProductsGrid = document.getElementById('all-products');
const cartItemsContainer = document.getElementById('cart-items');
const emptyCart = document.getElementById('empty-cart');
const cartSummary = document.getElementById('cart-summary');
const cartTotal = document.getElementById('cart-total');
const checkoutBtn = document.getElementById('checkout-btn');
const sortBy = document.getElementById('sort-by');
const searchInput = document.getElementById('search-input');
const searchBtn = document.getElementById('search-btn');
// DOM 元素
const profilePage = document.getElementById('profile-page');
const profileUsername = document.getElementById('profile-username');
const profileEmail = document.getElementById('profile-email');
const profileCartItems = document.getElementById('profile-cart-items');
const profileOrderHistory = document.getElementById('profile-order-history');

// 初始化应用
function initApp() {
    // 检查是否有登录用户
    const loggedInUser = localStorage.getItem('currentUser');
    if (loggedInUser) {
        currentUser = JSON.parse(loggedInUser);
        showAppPage();
    } else {
        showLoginPage();
    }
    
    // 更新购物车数量
    updateCartCount();
    
    // 加载商品
    loadFeaturedProducts();
    loadAllProducts();
    
    // 如果购物车有商品，显示购物车摘要
    if (cart.length > 0) {
        emptyCart.style.display = 'none';
        renderCartItems();
        updateCartSummary();
    }
    
}

// 显示登录页面
function showLoginPage() {
    loginPage.classList.add('active');
    registerPage.classList.remove('active');
    appPage.classList.remove('active');
}

// 显示注册页面
function showRegisterPage() {
    loginPage.classList.remove('active');
    registerPage.classList.add('active');
    appPage.classList.remove('active');
}

// 显示应用主页面
function showAppPage() {
    loginPage.classList.remove('active');
    registerPage.classList.remove('active');
    appPage.classList.add('active');
    sidebarUsername.textContent = currentUser.username;
}

// 登录功能
loginForm.addEventListener('submit', function(e) {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    const user = users.find(u => u.username === username && u.password === password);
    
    if (user) {
        currentUser = user;
        localStorage.setItem('currentUser', JSON.stringify(currentUser));
        showAppPage();
    } else {
        alert('用户名或密码错误！');
    }
});

// 注册功能
registerForm.addEventListener('submit', function(e) {
    e.preventDefault();
    const username = document.getElementById('reg-username').value;
    const email = document.getElementById('reg-email').value;
    const password = document.getElementById('reg-password').value;
    const confirmPassword = document.getElementById('reg-confirm-password').value;
    
    if (password !== confirmPassword) {
        alert('两次输入的密码不一致！');
        return;
    }
    
    if (users.some(u => u.username === username)) {
        alert('用户名已存在！');
        return;
    }
    
    if (users.some(u => u.email === email)) {
        alert('邮箱已被注册！');
        return;
    }
    
    const newUser = { username, email, password };
    users.push(newUser);
    alert('注册成功！请登录');
    showLoginPage();
    registerForm.reset();
});

// 切换登录/注册页面
showRegisterLink.addEventListener('click', function(e) {
    e.preventDefault();
    showRegisterPage();
});

showLoginLink.addEventListener('click', function(e) {
    e.preventDefault();
    showLoginPage();
});

// 登出功能
logoutBtn.addEventListener('click', function(e) {
    e.preventDefault();
    currentUser = null;
    localStorage.removeItem('currentUser');
    showLoginPage();
});

// 侧边栏菜单切换
menuToggle.addEventListener('click', function() {
    sidebar.classList.toggle('active');
});

// 关闭侧边栏当点击内容区域
document.querySelector('.main-content').addEventListener('click', function() {
    if (sidebar.classList.contains('active')) {
        sidebar.classList.remove('active');
    }
});

// 导航菜单点击事件
function handleNavigation(e) {
    e.preventDefault();
    const page = this.getAttribute('data-page');
    
    // 隐藏所有内容页面
    contentPages.forEach(p => p.classList.remove('active'));
    
    // 显示选中的页面
    document.getElementById(`${page}-page`).classList.add('active');
    
    // 更新活动菜单项
    menuItems.forEach(item => item.classList.remove('active'));
    this.classList.add('active');
    
    // 更新底部导航活动项
    footerItems.forEach(item => item.classList.remove('active'));
    document.querySelector(`.footer-item[data-page="${page}"]`).classList.add('active');
    
    // 关闭侧边栏
    sidebar.classList.remove('active');
    
    // 如果是购物车页面，更新内容
    if (page === 'cart') {
        if (cart.length === 0) {
            emptyCart.style.display = 'block';
            cartSummary.style.display = 'none';
        } else {
            emptyCart.style.display = 'none';
            cartSummary.style.display = 'flex';
            renderCartItems();
            updateCartSummary();
        }
    }
}

menuItems.forEach(item => item.addEventListener('click', handleNavigation));
footerItems.forEach(item => item.addEventListener('click', handleNavigation));

// 加载特色商品
function loadFeaturedProducts() {
    featuredProductsGrid.innerHTML = '';
    const featuredProducts = products.slice(0, 4); // 取前4个作为特色商品
    
    featuredProducts.forEach(product => {
        const productCard = createProductCard(product);
        featuredProductsGrid.appendChild(productCard);
    });
}

// 加载所有商品
function loadAllProducts() {
    allProductsGrid.innerHTML = '';
    
    products.forEach(product => {
        const productCard = createProductCard(product);
        allProductsGrid.appendChild(productCard);
    });
}

// 创建商品卡片
function createProductCard(product) {
    const productCard = document.createElement('div');
    productCard.className = 'product-card';
    productCard.setAttribute('data-id', product.id);
    
    productCard.innerHTML = `
        <div class="product-image">
            <img src="${product.image}" alt="${product.name}">
        </div>
        <div class="product-info">
            <h3 class="product-name">${product.name}</h3>
            <div>
                <span class="product-price">¥${product.price.toFixed(2)}</span>
                ${product.originalPrice ? `<span class="product-original-price">¥${product.originalPrice.toFixed(2)}</span>` : ''}
            </div>
            <div class="product-sales">销量: ${product.sales}</div>
            <button class="add-to-cart" data-id="${product.id}">加入购物车</button>
        </div>
    `;
    
    // 添加点击事件，查看商品详情
    productCard.addEventListener('click', function(e) {
        // 如果点击的是加入购物车按钮，则不跳转详情页
        if (e.target.classList.contains('add-to-cart')) {
            return;
        }
        showProductDetail(product.id);
    });
    
    return productCard;
}

// 显示商品详情
function showProductDetail(productId) {
    const product = products.find(p => p.id == productId);
    if (!product) return;
    
    // 隐藏所有内容页面
    contentPages.forEach(p => p.classList.remove('active'));
    
    // 填充商品详情数据
    document.getElementById('product-name').textContent = product.name;
    document.getElementById('product-price').textContent = `¥${product.price.toFixed(2)}`;
    document.getElementById('product-original-price').textContent = product.originalPrice ? `¥${product.originalPrice.toFixed(2)}` : '';
    document.getElementById('product-sales').textContent = product.sales;
    document.getElementById('product-stock').textContent = product.stock;
    document.getElementById('product-description-content').textContent = product.description;
    document.getElementById('product-main-image').src = product.image;
    document.getElementById('product-quantity').value = 1;
    
    // 显示商品详情页
    document.getElementById('product-detail-page').classList.add('active');
}

// 商品排序
sortBy.addEventListener('change', function() {
    const sortValue = this.value;
    let sortedProducts = [...products];
    
    switch(sortValue) {
        case 'price-asc':
            sortedProducts.sort((a, b) => a.price - b.price);
            break;
        case 'price-desc':
            sortedProducts.sort((a, b) => b.price - a.price);
            break;
        case 'sales':
            sortedProducts.sort((a, b) => b.sales - a.sales);
            break;
        default:
            // 默认排序（按原始顺序）
            break;
    }
    
    // 重新加载排序后的商品
    allProductsGrid.innerHTML = '';
    sortedProducts.forEach(product => {
        const productCard = createProductCard(product);
        allProductsGrid.appendChild(productCard);
    });
});

// 搜索功能
searchBtn.addEventListener('click', function() {
    const keyword = searchInput.value.trim().toLowerCase();
    
    if (!keyword) {
        loadAllProducts();
        return;
    }
    
    const filteredProducts = products.filter(product => 
        product.name.toLowerCase().includes(keyword) || 
        product.description.toLowerCase().includes(keyword) ||
        product.category.toLowerCase().includes(keyword)
    );
    
    allProductsGrid.innerHTML = '';
    
    if (filteredProducts.length === 0) {
        allProductsGrid.innerHTML = '<p class="no-results">没有找到相关商品</p>';
    } else {
        filteredProducts.forEach(product => {
            const productCard = createProductCard(product);
            allProductsGrid.appendChild(productCard);
        });
    }
    
    // 显示商品列表页
    contentPages.forEach(p => p.classList.remove('active'));
    document.getElementById('products-page').classList.add('active');
});

// 商品数量增减
document.getElementById('increase-qty').addEventListener('click', function() {
    const quantityInput = document.getElementById('product-quantity');
    let quantity = parseInt(quantityInput.value);
    const productId = document.getElementById('product-detail-page').getAttribute('data-id');
    const product = products.find(p => p.id == productId);
    
    if (quantity < product.stock) {
        quantityInput.value = quantity + 1;
    } else {
        alert('已达到最大库存数量');
    }
});

document.getElementById('decrease-qty').addEventListener('click', function() {
    const quantityInput = document.getElementById('product-quantity');
    let quantity = parseInt(quantityInput.value);
    
    if (quantity > 1) {
        quantityInput.value = quantity - 1;
    }
});

// 加入购物车按钮事件委托（处理动态生成的元素）
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('add-to-cart')) {
        const productId = e.target.getAttribute('data-id');
        addToCart(productId, 1);
    }
});

// 添加到购物车
function addToCart(productId, quantity = 1) {
    const product = products.find(p => p.id == productId);
    if (!product) return;
    
    // 检查购物车是否已有该商品
    const existingItem = cart.find(item => item.id == productId);
    
    if (existingItem) {
        // 检查库存是否足够
        if (existingItem.quantity + quantity > product.stock) {
            alert('购物车中该商品数量已达到库存上限');
            return;
        }
        existingItem.quantity += quantity;
    } else {
        // 检查库存是否足够
        if (quantity > product.stock) {
            alert('库存不足');
            return;
        }
        cart.push({
            id: product.id,
            name: product.name,
            price: product.price,
            image: product.image,
            quantity: quantity
        });
    }
    
    // 更新本地存储
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新购物车数量显示
    updateCartCount();
    
    // 显示添加成功提示
    alert(`${product.name} 已添加到购物车`);
}

// 更新购物车数量显示
function updateCartCount() {
    const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
    cartCount.textContent = totalItems;
}

// 渲染购物车商品
function renderCartItems() {
    cartItemsContainer.innerHTML = '';
    
    cart.forEach(item => {
        const product = products.find(p => p.id == item.id);
        if (!product) return;
        
        const cartItem = document.createElement('div');
        cartItem.className = 'cart-item';
        cartItem.setAttribute('data-id', item.id);
        
        cartItem.innerHTML = `
            <div class="cart-item-image">
                <img src="${item.image}" alt="${item.name}">
            </div>
            <div class="cart-item-details">
                <h4 class="cart-item-name">${item.name}</h4>
                <div class="cart-item-price">¥${item.price.toFixed(2)}</div>
                <div class="cart-item-actions">
                    <div class="quantity-selector">
                        <button class="decrease-qty">-</button>
                        <input type="number" class="item-quantity" value="${item.quantity}" min="1" max="${product.stock}">
                        <button class="increase-qty">+</button>
                    </div>
                    <span class="remove-item">删除</span>
                </div>
            </div>
        `;
        
        cartItemsContainer.appendChild(cartItem);
    });
    
    // 添加购物车商品事件监听
    addCartItemEventListeners();
}

// 添加购物车商品事件监听
function addCartItemEventListeners() {
    // 数量增减
    document.querySelectorAll('.increase-qty').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartItem = this.closest('.cart-item');
            const productId = cartItem.getAttribute('data-id');
            const quantityInput = cartItem.querySelector('.item-quantity');
            const product = products.find(p => p.id == productId);
            
            let quantity = parseInt(quantityInput.value);
            
            if (quantity < product.stock) {
                quantityInput.value = quantity + 1;
                updateCartItemQuantity(productId, quantity + 1);
            } else {
                alert('已达到最大库存数量');
            }
        });
    });
    
    document.querySelectorAll('.decrease-qty').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartItem = this.closest('.cart-item');
            const productId = cartItem.getAttribute('data-id');
            const quantityInput = cartItem.querySelector('.item-quantity');
            
            let quantity = parseInt(quantityInput.value);
            
            if (quantity > 1) {
                quantityInput.value = quantity - 1;
                updateCartItemQuantity(productId, quantity - 1);
            }
        });
    });
    
    // 手动输入数量
    document.querySelectorAll('.item-quantity').forEach(input => {
        input.addEventListener('change', function() {
            const cartItem = this.closest('.cart-item');
            const productId = cartItem.getAttribute('data-id');
            const product = products.find(p => p.id == productId);
            let quantity = parseInt(this.value);
            
            if (isNaN(quantity)) {
                this.value = 1;
                quantity = 1;
            }
            
            if (quantity < 1) {
                this.value = 1;
                quantity = 1;
            }
            
            if (quantity > product.stock) {
                this.value = product.stock;
                quantity = product.stock;
                alert('已达到最大库存数量');
            }
            
            updateCartItemQuantity(productId, quantity);
        });
    });
    
    // 删除商品
    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartItem = this.closest('.cart-item');
            const productId = cartItem.getAttribute('data-id');
            removeCartItem(productId);
        });
    });
}

// 更新购物车商品数量
function updateCartItemQuantity(productId, quantity) {
    const item = cart.find(item => item.id == productId);
    if (item) {
        item.quantity = quantity;
        localStorage.setItem('cart', JSON.stringify(cart));
        updateCartCount();
        updateCartSummary();
    }
}

// 从购物车移除商品
function removeCartItem(productId) {
    cart = cart.filter(item => item.id != productId);
    localStorage.setItem('cart', JSON.stringify(cart));
    
    if (cart.length === 0) {
        emptyCart.style.display = 'block';
        cartSummary.style.display = 'none';
        cartItemsContainer.innerHTML = ''; // 清空购物车商品列表
    } else {
        renderCartItems();
        updateCartSummary();
    }
    
    updateCartCount();
}

// 更新购物车汇总
function updateCartSummary() {
    const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    cartTotal.textContent = `¥${total.toFixed(2)}`;
    
    // 如果有商品，启用结算按钮
    checkoutBtn.disabled = cart.length === 0;
}

// 结算按钮点击事件
checkoutBtn.addEventListener('click', function() {
    if (cart.length === 0) return;
    
    // 这里可以添加结算逻辑，比如跳转到结算页面
    alert('结算功能将在下一步实现');
});

// 商品详情页加入购物车按钮
document.getElementById('add-to-cart-btn').addEventListener('click', function() {
    const productId = document.getElementById('product-detail-page').getAttribute('data-id');
    const quantity = parseInt(document.getElementById('product-quantity').value);
    
    addToCart(productId, quantity);
});

// 显示“我的”页面时填充用户信息
function showProfilePage() {
    contentPages.forEach(p => p.classList.remove('active'));
    document.getElementById('profile-page').classList.add('active');
    document.getElementById('profile-username').textContent = currentUser.username;
    document.getElementById('profile-email').textContent = currentUser.email;

    // 更新活动菜单项
    menuItems.forEach(item => item.classList.remove('active'));
    document.querySelector('.menu-item[data-page="profile"]').classList.add('active');

    // 更新底部导航活动项
    footerItems.forEach(item => item.classList.remove('active'));
    document.querySelector('.footer-item[data-page="profile"]').classList.add('active');

    // 关闭侧边栏
    sidebar.classList.remove('active');
}

// 处理“我的”页面菜单项点击事件
function handleProfileNavigation(e) {
    e.preventDefault();
    const page = this.getAttribute('data-page');
    if (page === 'cart') {
        // 跳转到购物车页面
        handleNavigation.call({ getAttribute: () => 'cart' }, e);
    } else if (page === 'orders') {
        // 这里可以添加历史订单页面的逻辑
        alert('历史订单页面将在下一步实现');
    }
}

// “我的”页面退出登录按钮点击事件
document.getElementById('profile-logout-btn').addEventListener('click', function(e) {
    e.preventDefault();
    currentUser = null;
    localStorage.removeItem('currentUser');
    showLoginPage();
});

// 为“我的”页面菜单项添加点击事件监听器
document.querySelectorAll('.profile-menu-item').forEach(item => item.addEventListener('click', handleProfileNavigation));

// 修改导航菜单点击事件处理函数，添加对“我的”页面的支持
function handleNavigation(e) {
    e.preventDefault();
    const page = this.getAttribute('data-page');

    // 隐藏所有内容页面
    contentPages.forEach(p => p.classList.remove('active'));

    // 显示选中的页面
    if (page === 'profile') {
        showProfilePage();
    } else {
        document.getElementById(`${page}-page`).classList.add('active');
    }

    // 更新活动菜单项
    menuItems.forEach(item => item.classList.remove('active'));
    this.classList.add('active');

    // 更新底部导航活动项
    footerItems.forEach(item => item.classList.remove('active'));
    document.querySelector(`.footer-item[data-page="${page}"]`).classList.add('active');

    // 关闭侧边栏
    sidebar.classList.remove('active');

    // 如果是购物车页面，更新内容
    if (page === 'cart') {
        if (cart.length === 0) {
            emptyCart.style.display = 'block';
            cartSummary.style.display = 'none';
        } else {
            emptyCart.style.display = 'none';
            cartSummary.style.display = 'flex';
            renderCartItems();
            updateCartSummary();
        }
    }
}


// 初始化应用
initApp();